package wang.xsports.upload.controller;

import java.io.File;

import org.json.JSONException;

import wang.xsports.upload.consts.Consts;

import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.net.CallRet;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.RSClient;

public class UploadController extends Controller {
    public void upload() throws AuthException, JSONException {
        UploadFile uploadFile = getFile("f");
        File file = uploadFile.getFile();


        // 请确保该bucket已经存在
        PutPolicy putPolicy = new PutPolicy(Consts.BUCKET_NAME);
        String uptoken = putPolicy.token(Consts.mac);
        PutExtra extra = new PutExtra();
        String key = String.valueOf(System.nanoTime());
        PutRet ret = IoApi.putFile(uptoken, key, file, extra);
        System.out.println("上传结果:" + ret);
        String uploadUrl = Consts.IMAGEURL_PREFIX + "//" + key;
        renderHtml("你上传的图片：<a href=\"" + uploadUrl + "\"><img src=\"" + uploadUrl + "\"/></a>");
    }

    public void delete() {
        String key = getPara("key");
        RSClient client = new RSClient(Consts.mac);
        CallRet ret = client.delete(Consts.BUCKET_NAME, key);
        System.out.println("删除结果:" + ret.response);
        renderText(ret.toString());
    }
}
